// 购物车功能实现

// 初始化购物车
let cart = JSON.parse(localStorage.getItem('cart')) || [];

// 更新购物车计数
function updateCartCount() {
  const cartCountElement = document.getElementById('cart-count');
  if (cartCountElement) {
    const totalItems = cart.reduce((total, item) => total + item.quantity, 0);
    cartCountElement.textContent = totalItems;
  }
}

// 添加商品到购物车
function addToCart(productId) {
  // 查找商品信息
  const product = products.find(p => p.id === productId);
  if (!product) return;

  // 检查购物车中是否已有该商品
  const existingItem = cart.find(item => item.id === productId);

  if (existingItem) {
    // 如果已存在，增加数量
    existingItem.quantity += 1;
  } else {
    // 如果不存在，添加新商品
    cart.push({
      id: product.id,
      name: product.name,
      price: product.price,
      image: product.image,
      quantity: 1
    });
  }

  // 保存到本地存储
  saveCart();

  // 更新购物车计数
  updateCartCount();

  // 显示添加成功提示
  showToast(`已将 ${product.name} 添加到购物车`);
}

// 从购物车中移除商品
function removeFromCart(productId) {
  cart = cart.filter(item => item.id !== productId);
  saveCart();
  updateCartCount();

  // 如果在购物车页面，更新购物车显示
  if (window.location.pathname.includes('cart.html')) {
    renderCart();
  }
}

// 更新购物车中商品数量
function updateQuantity(productId, quantity) {
  const item = cart.find(item => item.id === productId);
  if (item) {
    item.quantity = Math.max(1, quantity); // 确保数量至少为1
    saveCart();
    updateCartCount();

    // 如果在购物车页面，更新购物车显示
    if (window.location.pathname.includes('cart.html')) {
      renderCart();
    }
  }
}

// 保存购物车到本地存储
function saveCart() {
  localStorage.setItem('cart', JSON.stringify(cart));
}

// 清空购物车
function clearCart() {
  cart = [];
  saveCart();
  updateCartCount();

  // 如果在购物车页面，更新购物车显示
  if (window.location.pathname.includes('cart.html')) {
    renderCart();
  }
}

// 计算购物车总价
function calculateTotal() {
  return cart.reduce((total, item) => total + (item.price * item.quantity), 0);
}

// 显示提示消息
function showToast(message) {
  // 创建toast元素
  const toast = document.createElement('div');
  toast.className = 'toast';
  toast.textContent = message;

  // 添加样式
  toast.style.position = 'fixed';
  toast.style.bottom = '20px';
  toast.style.right = '20px';
  toast.style.backgroundColor = '#ff4d4f';
  toast.style.color = 'white';
  toast.style.padding = '10px 20px';
  toast.style.borderRadius = '4px';
  toast.style.boxShadow = '0 2px 8px rgba(0,0,0,0.2)';
  toast.style.zIndex = '1000';
  toast.style.opacity = '0';
  toast.style.transition = 'opacity 0.3s';

  // 添加到页面
  document.body.appendChild(toast);

  // 显示toast
  setTimeout(() => {
    toast.style.opacity = '1';
  }, 10);

  // 3秒后隐藏
  setTimeout(() => {
    toast.style.opacity = '0';
    setTimeout(() => {
      document.body.removeChild(toast);
    }, 300);
  }, 3000);
}

// 渲染商品列表
function renderProducts() {
  const productsGrid = document.getElementById('products-grid');
  if (!productsGrid) return;

  productsGrid.innerHTML = '';

  products.forEach(product => {
    const productCard = document.createElement('div');
    productCard.className = 'product-card';

    productCard.innerHTML = `
            <a href="product.html?id=${product.id}">
                <img src="${product.image || 'images/51290b9fb3b08b5ca7baa78147bf2b44.webp'}" alt="${product.name}" class="product-image">
            </a>
            <div class="product-info">
                <h3 class="product-name">${product.name}</h3>
                <div class="product-price">
                    <span class="current-price">¥${product.price.toFixed(2)}</span>
                    <span class="original-price">¥${product.originalPrice.toFixed(2)}</span>
                    <span class="discount">${product.discount}</span>
                </div>
                <div class="product-tags">
                    ${product.tags.map(tag => `<span class="tag">${tag}</span>`).join('')}
                </div>
                <button class="add-to-cart" onclick="addToCart(${product.id})">加入购物车</button>
            </div>
        `;

    productsGrid.appendChild(productCard);
  });
}

// 渲染商品详情
function renderProductDetail() {
  const productDetail = document.getElementById('product-detail');
  if (!productDetail) return;

  // 从URL获取商品ID
  const urlParams = new URLSearchParams(window.location.search);
  const productId = parseInt(urlParams.get('id'));

  // 查找商品
  const product = products.find(p => p.id === productId);

  if (!product) {
    productDetail.innerHTML = '<p>商品不存在</p>';
    return;
  }

  productDetail.innerHTML = `
        <div class="product-detail-image-container">
            <img src="${product.image || 'images/51290b9fb3b08b5ca7baa78147bf2b44.webp'}" alt="${product.name}" class="product-detail-image">
        </div>
        <div class="product-detail-info">
            <h1 class="product-name">${product.name}</h1>
            <div class="product-price">
                <span class="current-price">¥${product.price.toFixed(2)}</span>
                <span class="original-price">¥${product.originalPrice.toFixed(2)}</span>
                <span class="discount">${product.discount}</span>
            </div>
            <div class="product-tags">
                ${product.tags.map(tag => `<span class="tag">${tag}</span>`).join('')}
            </div>
            <p class="product-description">${product.description}</p>
            <p>库存: ${product.stock}件</p>
            <button class="add-to-cart" onclick="addToCart(${product.id})">加入购物车</button>
        </div>
    `;
}

// 渲染购物车
function renderCart() {
  const cartList = document.getElementById('cart-list');
  const cartSummary = document.getElementById('cart-summary');

  if (!cartList || !cartSummary) return;

  if (cart.length === 0) {
    cartList.innerHTML = '<div class="empty-cart">购物车是空的，去<a href="index.html">选购商品</a>吧！</div>';
    cartSummary.innerHTML = '';
    return;
  }

  cartList.innerHTML = '';

  cart.forEach(item => {
    const cartItem = document.createElement('div');
    cartItem.className = 'cart-item';

    cartItem.innerHTML = `
            <img src="${item.image || 'images/51290b9fb3b08b5ca7baa78147bf2b44.webp'}" alt="${item.name}" class="cart-item-image">
            <div class="cart-item-name">${item.name}</div>
            <div class="cart-item-quantity">
                <button class="quantity-btn" onclick="updateQuantity(${item.id}, ${item.quantity - 1})">-</button>
                <input type="number" class="quantity-input" value="${item.quantity}" min="1" onchange="updateQuantity(${item.id}, parseInt(this.value))">
                <button class="quantity-btn" onclick="updateQuantity(${item.id}, ${item.quantity + 1})">+</button>
            </div>
            <div class="cart-item-price">¥${(item.price * item.quantity).toFixed(2)}</div>
            <button class="remove-item" onclick="removeFromCart(${item.id})">删除</button>
        `;

    cartList.appendChild(cartItem);
  });

  const total = calculateTotal();
  cartSummary.innerHTML = `
        <div class="cart-summary">
            <span>总计:</span>
            <span class="cart-total">¥${total.toFixed(2)}</span>
        </div>
        <button class="add-to-cart" onclick="alert('结算功能尚未实现')">结算</button>
        <button class="clear-cart" onclick="clearCart()">清空购物车</button>
    `;
}

// 页面加载时初始化
document.addEventListener('DOMContentLoaded', function() {
  updateCartCount();

  // 根据当前页面执行不同的渲染
  if (window.location.pathname.endsWith('index.html') || window.location.pathname.endsWith('/')) {
    renderProducts();
  } else if (window.location.pathname.includes('product.html')) {
    renderProductDetail();
  } else if (window.location.pathname.includes('cart.html')) {
    renderCart();
  }
});